
/*
 * Copyright (C) 2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: DateField.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;

import org.dellroad.sidekar.util.PackedLong;
import org.dellroad.stuff.string.DateEncoder;
import org.dellroad.stuff.string.ParseContext;

/**
 * {@link Date} field.
 *
 * @see org.dellroad.sidekar.annotation.SidekarField
 */
public final class DateField extends AtomicField<Date> {

    DateField(String name, Entity<?> entity) {
        super(name, entity, Date.class);
    }

    @Override
    public void visit(FieldSwitch fieldSwitch) {
        fieldSwitch.caseDateField(this);
    }

    @Override
    public void encode(DataOutputStream output, Date value) throws IOException {
        if (value == null) {
            output.write(-1);
            return;
        }
        output.writeByte(0);
        PackedLong.write(output, value.getTime());
    }

    @Override
    public Date decode(DataInputStream input) throws IOException {
        byte nullbyte = input.readByte();
        if (nullbyte == -1)
            return null;
        return new Date(PackedLong.read(input));
    }

    @Override
    public String toString(Date value) {
        if (value == null)
            return "null";
        return DateEncoder.encode(value);
    }

    @Override
    public Date fromString(ParseContext ctx) {
        if (ctx.tryLiteral("null"))
            return null;
        return DateEncoder.decode(ctx.matchPrefix(DateEncoder.PATTERN).group());
    }
}

